package com.springboot.demo.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;

import com.springboot.demo.io.Constants;

/**
 * AIO客户端
 *
 * @author supu
 * @date 2019-12-03 17:32
 **/
public class AIOClient implements Runnable {
    private AsynchronousSocketChannel socketChannel;

    private Integer index;

    public AIOClient(Integer index) {
        try {
            this.index = index;
            // 打开通道
            socketChannel = AsynchronousSocketChannel.open();
            // 创建连接
            socketChannel.connect(new InetSocketAddress(Constants.HOST,Constants.AIO_PORT));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        String content = index + " -> 客户端数据";
        try {
            socketChannel.write(ByteBuffer.wrap(content.getBytes())).get();
            ByteBuffer byteBuffer = ByteBuffer.allocate(Constants.BUFFER_SIZE);
            while (true){
                int count = socketChannel.read(byteBuffer).get();
                byteBuffer.flip();
                if(count == -1){
                    continue;
                }
                byte[] responseBytes = new byte[byteBuffer.remaining()];
                // 将缓冲区的数据放入到 byte数组中
                byteBuffer.get(responseBytes);
                System.out.println(index+" 客户端 receive response :" + new String(responseBytes).trim());
                break;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            AIOClient aioClient = new AIOClient(i);
            new Thread(aioClient,"t-"+i).start();
        }
    }
}
